<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('import')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="exportExcel
            "
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{prop:'timeOfEntry', order: 'descending'}"
        >
          <el-table-column width="50" label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="100">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(row.id)"
              >分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :page-size="size"
            :current-page="page"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
          <!-- <el-pagination
            :current-page="currentPage4"
            :page-sizes="[100, 200, 300, 400]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /> -->
        </el-row>
      </el-card>
      <!-- 新增加员工 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">

        <addEmployees @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
      <!-- 生成二维码的图片 -->
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog">

        <el-row type="flex" justify="center">
          <!-- 画布是用来显示二维码图片 -->
          <canvas ref="myCanvas" />

        </el-row>

      </el-dialog>
      <el-dialog
        title="分配角色"

        :visible.sync="assignRoleDialog"
      >
        <AssignRole
          v-if="assignRoleDialog"
          :cur-id="curId"
          @success="assignRoleDialog = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import addEmployees from './empDialog.vue'
import { getEmployees, delEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
// console.log(employeesEnum, 'employeesEnum')
// console.log(employeesEnum.hireType, 'employeesEnum.hireType')
import QRCode from 'qrcode'

// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// console.log(hireType, 'hireType')
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addEmployees,
    AssignRole
  },
  data() {
    return {
      curId: '',
      assignRoleDialog: false,
      showCodeDialog: false,
      showDialog: false,
      list: [],
      page: 1,
      size: 10, // 每页显示的条数
      total: 0
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRole(id) {
      this.curId = id
      this.assignRoleDialog = true
    },
    // 显示二维码图片
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请传入正确的图片')
      }
    },
    exportExcel() {
    // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then((excel) => {
        const { tHeader, data } = this.transZhkeyToExcel(this.list)
        // import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhkeyToExcel(list) {
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 生成表头this.transZhkeyToExcel
      const one = list[0]
      if (!one) return
      // object.keys(one)===>['']
      const tHeader = Object.keys(one).map(item => {
        return mapInfo[item]
      })
      // console.log(tHeader, 'tHeader')
      const data = list.map(item => {
        return Object.values(item)
      })
      // console.log(data,'data');

      return { tHeader, data }
    },
    hDel(id) {
      this.$confirm('您确定要删除这个员工吗,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '权限',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已经取消'
        })
      })
    },
    hSuccess() {
      // 添加数据到最大的一页
      this.total++
      // 计算最大的页码
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      // 重新渲染
      this.loadEmployees()
      // 关闭弹层
      this.showDialog = false
    },

    handleCurrentChange(val) {
      this.page = val
      this.loadEmployees()
    },
    formatData(id) {
      return hireType[id] || '未知'
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        console.log(res, 'getEmployees')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
